package com.example.demo.Impl;

import com.example.demo.dto.ClazzManagementResultDTO;
import com.example.demo.entity.MbtiResult;
import com.example.demo.entity.Organization;
import com.example.demo.entity.Student;
import com.example.demo.repository.ClazzRepository;
import com.example.demo.repository.MbtiResultRepository;
import com.example.demo.repository.StudentRepository;
import com.example.demo.service.ClazzManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.example.demo.entity.Organization.OrgType;

import java.util.stream.Collectors;

@Service
public class ClazzManagementServiceImpl implements ClazzManagementService {

    @Autowired
    private ClazzRepository clazzRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private MbtiResultRepository mbtiResultRepository;

    @Override
    public List<ClazzManagementResultDTO> getAllClazzResults() {
        // 获取所有类型为 clazz 的组织（即所有班级）
        List<Organization> clazzList = clazzRepository.findByType(OrgType.clazz);

        List<ClazzManagementResultDTO> resultList = new ArrayList<>();

        for (Organization clazz : clazzList) {
            ClazzManagementResultDTO dto = new ClazzManagementResultDTO();
            dto.setClassId(clazz.getId());
            dto.setClassName(clazz.getName());

            // 获取专业和学院名称
            Organization major = clazz.getParent();
            Organization college = (major != null) ? major.getParent() : null;

            dto.setMajorName(major != null ? major.getName() : "");
            dto.setCollegeName(college != null ? college.getName() : "");

            // 获取该班级所有学生
            List<Student> students = studentRepository.findByClazzId(clazz.getId());

            List<ClazzManagementResultDTO.StudentResult> studentResults = students.stream().map(student -> {
                ClazzManagementResultDTO.StudentResult sr = new ClazzManagementResultDTO.StudentResult();
                sr.setStudentName(student.getName());
                sr.setStudentNo(student.getStudentNo());

                // 获取该学生最新的 MBTI 测试结果
                List<MbtiResult> results = mbtiResultRepository.findByStudentIdOrderByTestTimeDesc(student.getId());
                if (!results.isEmpty()) {
                    MbtiResult latest = results.get(0);
                    sr.setMbtiType(latest.getMbtiType());
                    sr.setTestTime(latest.getTestTime());
                }
                return sr;
            }).collect(Collectors.toList());

            dto.setStudents(studentResults);
            resultList.add(dto);
        }

        return resultList;
    }
}
